import {
  Image,
  Tag,
  Collapse,
  Modal,
  message,
  Empty,
  Select,
  ConfigProvider,
  DatePicker,
  Button,
  Pagination,
} from 'antd'
import {
  CaretRightOutlined,
  SearchOutlined,
  CloseCircleOutlined,
  UnorderedListOutlined,
} from '@ant-design/icons'
import './order.css'
import site from '../../assets/site.png'
import success from '../../assets/success.png'
import person from '../../assets/person.png'
import rider from '../../assets/rider.png'
import noting from '../../assets/noting.png'
import { useState, useEffect } from 'react'
import {
  riderList,
  assignOrder,
  userOrderList,
  storeOrderList,
  notDelivery,
  keywordList,
  userExport,
  storeExport,
} from '../../api/api'
import zhCN from 'antd/locale/zh_CN'
import locale from 'antd/locale/zh_CN'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
import { BASE_URL } from '../../utils/config'
function AddressOrder(props) {
  const [arr, setArr] = useState([1])
  useEffect(() => {
    getList()
    getKeywordList()
  }, [arr])
  // 分页
  const [page, setPage] = useState(1)
  // 分页总页数
  const [pageTotal, setPageTotal] = useState(0)
  // 切换页码
  const onPageChange = (e) => {
    console.log('切换页码', e)
    setPage(e)
    // getList(selectVal, e)
  }
  const [selectKey, setSelectKey] = useState(1)
  const [addressList, setAdderssList] = useState([])
  // 获取关键词列表
  const getKeywordList = () => {
    keywordList().then((res) => {
      console.log('关键词列表', res)
      setAdderssList(res.data)
    })
  }
  const [keyword, setKeyword] = useState([])
  // 选择器修改
  const handleChange = (value) => {
    console.log(value)
    setKeyword(value)
  }
  const [isEmpty, setEmpty] = useState(false)
  // 去配送
  const [deliveryOrderId, setDeliveryOrderId] = useState('')
  const delivery = (e, item) => {
    console.log('item---', item)
    e.stopPropagation()
    let idList = []
    item.order.forEach((element) => {
      idList.push(element.order_id)
    })
    let orderId = idList.join(',')
    setDeliveryOrderId(orderId)
    showListModal()
  }
  // 无法配送弹窗
  const [notModalOpen, setNotModalOpen] = useState(false)
  const showNotModal = (e, item) => {
    console.log(e)
    console.log('---item', item)
    e.stopPropagation()
    let idList = []
    item.order.forEach((element) => {
      idList.push(element.order_id)
    })
    let orderId = idList.join(',')
    setDeliveryOrderId(orderId)
    setNotModalOpen(true)
  }
  const handleNotCancel = () => {
    setNotModalOpen(false)
  }
  // 选择配送员弹窗
  const [listModalOpen, setListModalOpen] = useState(false)
  const showListModal = () => {
    setListModalOpen(true)
    getRiderList()
  }
  const handleListCancel = () => {
    setListModalOpen(false)
  }
  const [photoList, setPhotoList] = useState([])
  const [riderName, setRiderName] = useState('')

  // 查看照片
  const checkPhoto = (item) => {
    console.log(item)
    setPhotoList(item.photo)
    setRiderName(item.rider_name)
    showFulfillModal()
  }
  const checkDelivery = (item) => {
    showIndcModal()
    setRiderName(item.rider_name)
  }

  const [items3, setItems3] = useState([])
  const [orderList, setOrderList] = useState([])

  // 开始时间

  const [start, setStart] = useState('')
  const onChangeStart = (date, dateStr) => {
    console.log('开始时间', date, dateStr)
    setStart(dateStr)
  }
  // 结束时间

  const [end, setEnd] = useState('')

  const onChangeEnd = (date, dateStr) => {
    console.log('结束时间', date, dateStr)
    setEnd(dateStr)
  }
  // 搜索
  const search = () => {
    getList()
  }
  const [dateKey, setDateKey] = useState(1)

  // 重置
  const reset = () => {
    setKeyword([])
    setSelectKey(2)
    setDateKey(2)
    setTimeout(() => {
      setDateKey(1)
      setSelectKey(1)
    }, 0)
    setArr([])
  }
  // 数据导出
  const exportExcel = () => {
    if (props.orderType == 1) {
      //用户预订单数据导出

      let keyword2 = keyword.join(',')
      let url = `${BASE_URL}/kitchen/reserve/userReserveListExport?type=2&keyword=${keyword2}&starttime=${start}&overtime=${end}`
      window.open(url)
    } else {
      let keyword2 = keyword.join(',')
      let url = `${BASE_URL}/kitchen/reserve/storeReserveListExport?type=2&keyword=${keyword2}&starttime=${start}&overtime=${end}`
      window.open(url)
    }
  }
  // 获取订单列表
  const getList = () => {
    if (props.orderType == 1) {
      userOrderList({
        type: 2,
        page: page,
        num: 10,
        keyword: keyword.join(','),
        starttime: start,
        overtime: end,
      }).then((res) => {
        console.log('获取订单列表123用户---', res)
        setOrderList(res.data)
        let mylist = res.data
        console.log('---mylist', mylist)
        if (mylist.length == 0) {
          setEmpty(true)
          return
        }
        setEmpty(false)
        let items2 = []

        for (let i = 0; i < mylist.length; i++) {
          let obj = {}
          obj.key = i
          obj.label = (
            <div className="justify-between ">
              <div className="align-center">
                <Image width={44} src={site} />
                <div className="ml15">
                  <div className="ft18">{mylist[i].address}</div>
                  {/* <div className="gray9 ft18">
                    订单数量：{mylist[i].item.leng}
                  </div> */}
                </div>
              </div>
              <div className="align-center">
                {/* <div
                  className="notdeliverBtn pointer"
                  onClick={(e) => showNotModal(e, mylist[i])}>
                  无法配送
                </div>

                <div
                  className="deliverBtn pointer"
                  onClick={(e) => {
                    delivery(e, mylist[i])
                  }}>
                  去配送
                </div> */}
                <div className="ft14 blue">展开</div>
              </div>
            </div>
          )
          obj.children = (
            <div>
              {mylist[i].item.map((item, index) => {
                return (
                  <div className="justify-between bggray bdbe pd20" key={index}>
                    <div className="align-start ">
                      <Image width={108} src={item.food_image} />
                      <div className="ml15">
                        <div className="ft18">
                          {item.food_name}
                          <Tag className="ml10">预订单</Tag>
                        </div>
                        <div className="mt15 gray9 ft16">x{item.number}</div>
                        <div className="mt20 ft14 gray6">
                          {/* <span>订单编号:{item.order_sn}</span>
                          <span className="ml20">
                            下单时间:{item.createtime_text}
                          </span>
                          <span className="ml20">联系方式:{item.mobile}</span>
                          <span className="ml20">
                            下单地址:
                            {item.address}
                          </span> */}
                        </div>
                      </div>
                    </div>
                    <div className="self-start align-center">
                      {item.photo && item.photo.length && item.status > 2 ? (
                        <div
                          className="deliverBtn pointer"
                          onClick={() => checkPhoto(item)}
                          style={{ marginRight: '10px' }}>
                          查看
                        </div>
                      ) : null}
                      {item.status == 2 ? (
                        <div
                          className="deliverBtn pointer"
                          onClick={() => checkDelivery(item)}
                          style={{ marginRight: '10px' }}>
                          查看
                        </div>
                      ) : null}
                      {/* <div className="">
                        {item.status == 1
                          ? '待配送'
                          : item.status == 2
                          ? '配送中'
                          : item.status == 3
                          ? '待评价'
                          : item.status == 4
                          ? '已完成'
                          : item.status == 100
                          ? '退款中'
                          : item.status == 101
                          ? '已退款'
                          : ''}
                      </div> */}
                    </div>
                  </div>
                )
              })}
            </div>
          )
          items2.push(obj)
          console.log(items2)
        }
        setItems3(items2)
      })
    } else {
      storeOrderList({
        type: 2,
      }).then((res) => {
        console.log('获取订单列表', res)
        setOrderList(res.data)
        let mylist = res.data
        console.log('---mylist', mylist)
        if (mylist.length == 0) {
          setEmpty(true)
          return
        }
        setEmpty(false)
        let items2 = []

        for (let i = 0; i < mylist.length; i++) {
          let obj = {}
          obj.key = i
          obj.label = (
            <div className="justify-between ">
              <div className="align-center">
                <Image width={44} src={site} />
                <div className="ml15">
                  <div className="ft18">{mylist[i].address}</div>
                  {/* <div className="gray9 ft18">
                    订单数量：{mylist[i].order_num}
                  </div> */}
                </div>
              </div>
              {/* <div className="align-center">
                <div
                  className="notdeliverBtn"
                  onClick={(e) => showNotModal(e, mylist[i])}>
                  无法配送
                </div>

                <div
                  className="deliverBtn"
                  onClick={(e) => {
                    delivery(e, mylist[i])
                  }}>
                  去配送
                </div>
                <div className="ft14 blue">展开</div>
              </div> */}
            </div>
          )
          obj.children = (
            <div>
              {mylist[i].item.map((item, index) => {
                return (
                  <div className="justify-between bggray bdbe pd20" key={index}>
                    <div className="align-start ">
                      <Image width={108} src={item.food_image} />
                      <div className="ml15">
                        <div className="ft18">
                          {item.food_name}
                          <Tag className="ml10">预订单</Tag>
                        </div>
                        <div className="mt15 gray9 ft16">x{item.number}</div>
                        {/* <div className="mt20 ft14 gray6">
                          <span>订单编号:{item.order_sn}</span>
                          <span className="ml20">
                            下单时间:{item.createtime_text}
                          </span>
                          <span className="ml20">联系方式:{item.mobile}</span>
                          <span className="ml20">
                            下单地址:
                            {item.address}
                          </span>
                        </div> */}
                      </div>
                    </div>
                    <div className="self-start align-center">
                      {item.photo && item.photo.length && item.status > 2 ? (
                        <div
                          className="deliverBtn pointer"
                          onClick={() => checkPhoto(item)}
                          style={{ marginRight: '10px' }}>
                          查看
                        </div>
                      ) : null}
                      {item.status == 2 ? (
                        <div
                          className="deliverBtn pointer"
                          onClick={() => checkDelivery(item)}
                          style={{ marginRight: '10px' }}>
                          查看
                        </div>
                      ) : null}
                      <div className="">
                        {item.status == 1
                          ? '待配送'
                          : item.status == 2
                          ? '配送中'
                          : item.status == 3
                          ? '待评价'
                          : item.status == 4
                          ? '已完成'
                          : item.status == 100
                          ? '退款中'
                          : item.status == 101
                          ? '已退款'
                          : ''}
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          )
          items2.push(obj)
          console.log(items2)
        }
        setItems3(items2)
      })
    }
  }
  const [ridersList, setRidersList] = useState([])
  const [currentIndex, setCurrentIndex] = useState(0)

  // 提交成功弹窗
  const [successOpen, setSuccessOpen] = useState(false)
  const showSuccessModal = () => {
    setSuccessOpen(true)
  }
  const handleSuccessCancel = () => {
    getList()
    setSuccessOpen(false)
  }
  // 配送中弹窗
  const [indcOpen, setIndcOpen] = useState(false)
  const showIndcModal = () => {
    setIndcOpen(true)
  }
  const handleIndcCancel = () => {
    setIndcOpen(false)
  }
  // 已完成弹窗
  const [fulfillOpen, setFulfillOpen] = useState(false)
  const showFulfillModal = () => {
    setFulfillOpen(true)
  }
  const handleFulfillCancel = () => {
    setFulfillOpen(false)
  }
  // 获取骑手列表
  const getRiderList = () => {
    riderList().then((res) => {
      console.log('骑手列表', res)
      setRidersList(res.data.list)
    })
  }
  // 选择骑手
  const chooseRider = (e, index) => {
    console.log('当前索引', index)
    setCurrentIndex(index)
  }
  // 提交配送员
  const submitRider = () => {
    const rider_id = ridersList[currentIndex].id
    assignOrder({
      rider_id: rider_id,
      order_id: deliveryOrderId,
    }).then((res) => {
      console.log('分配订单', res)
      if (res.code == 200) {
        getList()
        handleListCancel()
      }
    })
    showSuccessModal()
    // showIndcModal()
    // showFulfillModal()
  }
  // 确认无法配送
  const confirmNot = () => {
    notDelivery({
      order_id: deliveryOrderId,
    }).then((res) => {
      console.log('无法配送', res)
      if (res.code == 200) {
        message.info(res.msg)
        handleNotCancel()
      }
    })
  }

  return (
    <div className="pt10">
      <div className=" tabbox justify-between">
        <div className="align-center flex-wrap" style={{ width: '70%' }}>
          <Select
            key={selectKey}
            className="searchInput mb10 mr10"
            mode="multiple"
            allowClear
            style={{
              borderRadius: '5px',
              overflow: 'hidden',
              minWidth: '500px',
            }}
            placeholder="请选择地址"
            onChange={handleChange}
            options={addressList.map((item) => ({
              label: item.keyword,
              value: item.keyword,
            }))}
          />
          <ConfigProvider locale={locale}>
            {dateKey == 1 ? (
              <div key={dateKey}>
                <DatePicker
                  className="searchInput mb10"
                  placeholder="开始时间"
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  onChange={onChangeStart}
                />
                <span className="ml10 mr10">--</span>
                <DatePicker
                  className="mr10 searchInput mb10"
                  placeholder="结束时间"
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  onChange={onChangeEnd}
                />
              </div>
            ) : null}
          </ConfigProvider>
        </div>
        <div className="shrink0 mb10">
          <Button className="optbtn" icon={<SearchOutlined />} onClick={search}>
            查询
          </Button>
          <Button
            className="optbtn ml15"
            icon={<CloseCircleOutlined />}
            onClick={reset}
            style={{
              background: '#f5f6fa',
              border: '1px solid #f5f6fa',
            }}>
            重置
          </Button>
          <Button
            icon={<UnorderedListOutlined />}
            onClick={exportExcel}
            className="optbtn ml15">
            导出
          </Button>
        </div>
      </div>
      {/* 选择配送员弹窗 */}
      <Modal
        title="选择配送员"
        footer={null}
        open={listModalOpen}
        onCancel={handleListCancel}
        width="80%">
        <div className="">
          <div className="grid5">
            {ridersList.map((item, index) => {
              return (
                <div
                  className="flex-col"
                  onClick={(e) => {
                    chooseRider(e, index)
                  }}
                  key={index}>
                  <Image
                    className={
                      currentIndex == index
                        ? ' border radius5 hidden riderimg'
                        : ' radius5 hidden riderimg'
                    }
                    width={154}
                    height={210}
                    preview={false}
                    src={item.avatar}
                  />
                  <div className="tc mt15">{item.nickname}</div>
                </div>
              )
            })}
          </div>

          <div className="submit-btn1" onClick={submitRider}>
            确认提交
          </div>
        </div>
      </Modal>
      {/* 确认无法配送弹窗 */}
      <Modal
        title=" "
        footer={null}
        open={notModalOpen}
        onCancel={handleNotCancel}
        width="422px"
        centered={true}>
        <p className="tc ft20">确认无法配送吗?</p>
        <div className="justify-between">
          <div className="cancelBtn btmbtn" onClick={handleNotCancel}>
            取消
          </div>
          <div className="confirmBtn btmbtn" onClick={confirmNot}>
            确认
          </div>
        </div>
      </Modal>
      {/* 提交成功弹窗 */}
      <Modal
        title=" "
        footer={null}
        open={successOpen}
        onCancel={handleSuccessCancel}
        width="35%">
        <p className="tc ft20">提交成功</p>
        <div className="flex-col">
          <img src={success} className="successIcon" />
          <div className="align-center mt40">
            配送员：
            <img src={person} className="personIcon ml10 mr10" />
            {ridersList[currentIndex]?.nickname || ''}
          </div>
        </div>
      </Modal>
      {/* 配送中弹窗 */}
      <Modal
        title=" "
        footer={null}
        open={indcOpen}
        onCancel={handleIndcCancel}
        width="35%">
        <p className="tc ft20">正在配送中</p>
        <div className="flex-col">
          <img src={rider} className="riderIcon" />
          <div className="align-center mt40">
            配送员：
            <img src={person} className="personIcon ml10 mr10" />
            {riderName || ''}
          </div>
        </div>
      </Modal>
      {/* 已完成弹窗 */}
      <Modal
        title=" "
        footer={null}
        open={fulfillOpen}
        onCancel={handleFulfillCancel}>
        <p className="tc ft20">已完成</p>
        <div className="">
          <div className="align-center mt40">
            配送员：
            <img src={person} className="personIcon ml10 mr10" />
            {riderName || ''}
          </div>
          <div className="align-center mt40 mb30">
            <div className="self-start">拍摄照片：</div>
            <div className="grid3">
              {photoList.map((item, index) => {
                return (
                  <div className="mr20" key={index}>
                    <Image width={100} src={item} />
                    {/* <Image.PreviewGroup items={photoList}>
                    <Image width={200} src={item} />
                  </Image.PreviewGroup> */}
                  </div>
                )
              })}
            </div>
          </div>
        </div>
      </Modal>

      {isEmpty ? (
        <div style={{ marginTop: '150px' }}>
          <Empty image={noting} description="暂无数据" imageStyle={{}} />
        </div>
      ) : (
        <Collapse
          items={items3}
          expandIconPosition="end"
          className="collapse"
          collapsible="header"
          expandIcon={({ isActive }) => (
            <CaretRightOutlined
              style={{ color: '#168fff' }}
              rotate={isActive ? 90 : 0}
            />
          )}
          defaultActiveKey={[' ']}
        />
      )}
      {/* <div className="flex-cen m  t10">
        <ConfigProvider locale={zhCN}>
          <Pagination
            total={pageTotal}
            showSizeChanger={false}
            showQuickJumper
            onChange={(e) => onPageChange(e)}
            showTotal={(total) => `共 ${total} 条`}
          />
        </ConfigProvider>
      </div> */}
    </div>
  )
}
export default AddressOrder
